<style scoped>
  .content {
    margin-top: 20px;
    padding: 20px;
  }

  .survey-item {
    padding: 20px;
    /*margin-top: 20px;*/
    min-height: 200px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
  }

  .collect-num {
    margin-top: 20px;
    line-height: 50px;
  }

  .strong-font {
    font-weight: bold;
    color: black;
  }

  .cti-area {
    height: 60px;
    width: 100%;
    margin-top: 20px;
    bottom: 10px;
  }
</style>

<template>
  <div style="height: 100%;">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>坐席监控</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="cti-area">
      <el-card class="box-card" :body-style="{ padding: '0px' }">
        <el-row>
          <el-col :span="20">
            <el-button plain size="small" icon="el-icon-edit" @click="sign" v-if="isButtonDisabled('signIn')">
              签入
            </el-button>
            <el-button plain size="small" icon="el-icon-edit" @click="signOut" v-if="isButtonDisabled('signOut')">
              签出
            </el-button>
            <el-dropdown :disabled="agentStatus === -1">
              <el-button size="small">
                <i class="el-icon-user"></i>状态<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :disabled="agentStatus === 0" @click.native="changeAgentStatus(0)">空闲
                </el-dropdown-item>
                <el-dropdown-item :disabled="agentStatus === 6" @click.native="changeAgentStatus(6)">忙碌
                </el-dropdown-item>
                <el-dropdown-item :disabled="agentStatus === 7" @click.native="changeAgentStatus(7)">离开
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button size="small" icon="el-icon-video-camera" :disabled="agentStatus === -1" style="margin: 0px" @click="monitorHandler">监控
            </el-button>
            <el-button size="small" icon="el-icon-phone" style="margin: 0px" :disabled="isButtonDisabled('calling')">
              挂断
            </el-button>

            <el-button size="small" @click="testOpen()" :disabled="!survey.active">关闭并挂断</el-button>
          </el-col>

          <el-col :span="4">
            <el-row style="line-height: 30px;text-align: center; font-size: 14px">
              <el-col :span="6" style="border-left: 2px solid #e0dfdf;border-right: 2px solid #e0dfdf;">坐席</el-col>
              <el-col :span="6">{{ agentno }}</el-col>
              <el-col :span="6" style="border-left: 2px solid #e0dfdf;border-right: 2px solid #e0dfdf;">状态</el-col>
              <el-col :span="6" :style="{color: agentStatus === 0 ? 'green' : 'red'}">
                {{ agentStatus | agentStatusFilter }}
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <!--    <el-botton @click="survey.active = !survey.active">click</el-botton>-->
    <div>
      <el-collapse-transition>
        <div v-show="survey.active">
          <Survey @statusChange="surveyStatusChange" :survey-id="survey.id" :active="survey.active"
                  :phone="survey.phone" :agent-id="survey.agentUUID" :seat="agentno"></Survey>
        </div>
      </el-collapse-transition>
    </div>
    <div v-if="showMonitor">
      <el-collapse-transition>
        <div v-show="!survey.active" style="height: 700px">
          <el-tabs v-model="activeName">
            <el-tab-pane label="队列" name="queue" style="font-size: 14px;">
              <el-row>
                <el-col :span="4" v-for="(item, index) in monitor.roleQueueName" :key="index" @click.native="getQueueAgents(item, index)">
                  <el-card shadow="hover">
                    {{item}}
                  </el-card>
                </el-col>
                <el-col :span="4">
                  <el-button type="success" size="mini" shadow="hover" icon="el-icon-refresh" @click="syncQueue">
                    同步队列
                  </el-button>
                </el-col>
              </el-row>
              <el-divider></el-divider>

              <el-row>
                <el-col :span="3" v-for="(item, index) in monitor.currentQueueAgents" :key="index">
                  <el-card shadow="hover">
                    <div>{{item.agentNum}}</div>
                    <div :style="{color: agentStatusColor(item.status)}">{{item.status | agentStatusFilter}}</div>
                  </el-card>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="坐席组" name="group">
              <el-row>
                <el-col :span="4" v-for="(item, index) in monitor.roleAgentGroupName" :key="index" @click.native="getGroupAgents(item, index)">
                  <el-card shadow="hover">
                    {{item}}
                  </el-card>
                </el-col>
              </el-row>
              <el-divider></el-divider>

              <el-row>
                <el-col :span="3" v-for="(item, index) in monitor.currentGroupAgents" :key="index">
                  <el-card shadow="hover">
                    <div>{{item.agentNum}}</div>
                    <div :style="{color: agentStatusColor(item.status)}">{{item.status | agentStatusFilter}}</div>
                  </el-card>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-collapse-transition>
    </div>

  </div>
</template>

<script>
  import Pagination from "../../../components/Pagination";
  import {Loading} from 'element-ui';
  import {buttonDisable, err, info, mapMsg} from "../../../api/cti";
  import Survey from "../../../components/survey"
  import {syncQueueInfo} from "../../../api/baseMG"

  export default {
    data() {
      return {
        monitor: {
          roleAgentGroupNum: [],
          roleAgentGroupName: [],
          roleQueueNum: [],
          roleQueueName: [],
          currentQueueAgents: [],
          currentGroupAgents: []
        },
        activeName: 'queue',
        showMonitor: false,
        heartbeatId: null,
        agentStatus: -1,
        websocket: null,
        useWebrtc: 'yes',
        agentno: '8888',
        exten: '8888',
        pstnnumber: '82312340',
        password: 'svdata123',
        sipServer: 'tj.svdata.cn',
        sipPort: '7067',
        extenPwd: 'svdata123',
        autoAnswer: 'no',
        websocketUrl: 'wss://tj.svdata.cn/yscrm/websocket',
        survey: {
          id: null,
          active: false,
          phone: null,
          agentUUID: null
        }
      }
    },
    filters: {
      agentStatusFilter(data) {
        if (data == -1) {
          return '离线'
        }
        if (data == 0) {
          return '空闲'
        }
        if (data == 1) {
          return '振铃';
        }
        if (data == 2) {
          return '通话中'
        }
        if (data == 3) {
          return '保持'
        }
        if (data == 4) {
          return '后处理'
        }
        if (data == 5) {
          return '被占用'
        }
        if (data == 6) {
          return '忙碌'
        }
        if (data == 7) {
          return '离开'
        }
        if (data == 8) {
          return '仅呼出'
        }
        return '其他'
      }
    },
    created() {
      this.registerWebsocket()
      this.survey.id = parseInt(this.$route.query.id);
    },
    components: {
      Survey,
      Pagination
    },
    methods: {
      syncQueue() {
        syncQueueInfo(this.monitor.roleQueueName).then(resp => {
          info(resp.msg);
        })
      },
      agentStatusColor(status) {
        if(status === 0) {
          return 'green';
        }

        if(status === 2) {
          return 'red';
        }

        if(status === -1) {
          return 'rgb(46 46 46 / 36%)';
        }
        return "#303133"
      },
      getGroupAgents(params, i) {
        let message = "{'method':'getAgentsOfAgentgroup','agentno':'" + agentno + "','param1':'" + this.monitor.roleAgentGroupNum[i] + "'}";
        websocket.send(message);
      },
      getQueueAgents(params, i) {
        let message = "{'method':'getAgentsOfQueue','agentno':'" + agentno + "','param1':'" + this.monitor.roleQueueNum[i] + "'}";
        websocket.send(message);
      },
      monitorHandler() {
        this.showMonitor = !this.showMonitor;
        if (this.monitor.roleAgentGroupNum.length === 0) {
          method = "getAgentGroupList";
          send();
        }
        if (this.monitor.roleQueueNum.length === 0) {
          method = "getQueueList";
          send();
        }
      },
      callOutHandler() {
        this.$prompt('请输入要呼叫的号码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[0-9]+$/,
          inputErrorMessage: '请输入有效的外呼号码'
        }).then(({value}) => {
          var message = "{'method':'manualCallout','agentno':'" + agentno + "','pstnnumber':'" + pstnnumber + "','callee':'" + value + "','cusData':''}";
          websocket.send(message);
        }).catch(() => {
        });
      },
      testOpen() {
        if(this.survey.active) {
          this.survey.active = !this.survey.active;
        }
        hangUp();
      },
      // 接听
      toSipAnswer(json) {
        this.$confirm('来电提示，是否接听?', '信息', {
          confirmButtonText: '接听',
          cancelButtonText: '挂断',
          type: 'warning'
        }).then(() => {
          sipAnswer();
          let agentUuid = json.agentUuid;
          let customerNum = json.customerNum;
          if (!agentUuid) {
            throw Error("AgentUUID 不存在，请挂断后重试");
          }
          if (!customerNum) {
            throw Error("「外呼号」不存在，请挂断后重试");
          }
          this.survey.active = true;
          this.survey.agentUUID = agentUuid;
          this.survey.phone = customerNum;
        }).catch(err => {
          sipHangUp();
          this.survey.active = false;
        });
      },
      surveyStatusChange(data) {
        this.survey.active = data.active;
      },
      changeAgentStatus(status) {
        window.loading = Loading.service({
          lock: true,
          text: '玩命加载中......',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        changeStatus(status);
      },
      isButtonDisabled(btn) {
        return buttonDisable(btn, this.agentStatus);
      },
      sign() {
        window.loading = Loading.service({
          lock: true,
          text: '玩命加载中......',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        if (this.useWebrtc === "yes") {
          loadSipml();
          sipRegister();
        }
        method = "signout";
        send();
        setTimeout('delaySignin()', 3000);
      },
      signOut() {
        if (this.useWebrtc === "yes") {
          sipUnRegister();
        }
        method = "signout";
        send();
      },
      // 注册WebSocket服务
      registerWebsocket() {
        let that = this;
        window.websocketUrl = this.websocketUrl;
        window.agentno = this.agentno;
        window.exten = this.exten;
        window.pstnnumber = this.pstnnumber;
        window.password = this.password;

        window.sipServer = this.sipServer;
        window.sipPort = this.sipPort;
        window.extenPwd = this.extenPwd;
        window.autoAnswer = this.autoAnswer;
        window.useWebrtc = this.useWebrtc;
        if ('WebSocket' in window) {
          websocket = new WebSocket(this.websocketUrl);
          that.websocket = websocket;
        } else {
          alert('当前浏览器不支持WebSocket通信，座席功能将不能使用！')
        }

        window.websocket = this.websocket;

        this.websocket.onerror = function () {
          setMessageInnerHTML("error");
        };

        websocket.onopen = function (event) {
          setMessageInnerHTML("open");
          that.$message({
            type: 'success',
            message: '连接服务器成功'
          });
        };

        websocket.onmessage = function (event) {

          try {
            let jsonStr = JSON.parse(event.data);
            window.loading.close();
            that.wsEvent(jsonStr.type, jsonStr.status, jsonStr.method, jsonStr.retCode, jsonStr, this.agentStatus);
          } catch (e) {
            return false;
          }
        };

        websocket.onclose = function () {
          that.$message({
            type: 'error',
            message: '与服务器断开连接'
          });
        };

        //离开或刷新页面
        window.onbeforeunload = function () {
          //return '确认要退出页面吗?';
          if (this.websocket != null) {
            method = "signout";
            send();
            this.websocket.close();
          }
          if (this.useWebrtc === "yes") {
            sipUnRegister();
          }
        }
      },
      wsEvent(type, status, methodName, retCode, jsonStr, agentStatus) {
        if(jsonStr['agentno'] === this.agentno) {
          console.log(jsonStr);
        }
        if (type === 'response') {
          if (methodName === 'signin') {
            if (retCode === '-6') {
              err("请不要重复签入");
            } else if (retCode === '-11') {
              err("分机不在线，签入失败");
            } else if (retCode === '-12') {
              err("分机已被其他座席绑定，签入失败");
            } else if (retCode !== '0') {
              err("签入失败[ErrorCode:" + retCode + "]");
            }
          } else if (methodName === 'internal_call') {
            if (retCode === '-30') {
              err(mapMsg(jsonStr.retMessage, "内呼失败"));
            } else {
              err("内呼失败[ErrorCode:" + retCode + "]")
            }
          }
        } else if (type === 'event') {
          if (methodName === 'signin') {
            if (retCode === '0') {
              agentStatus = 1;
              method = "setAcsType";//通话结束后座席状态默认空闲
              send();
              if (heartbeatId >= 0) {
                clearInterval(heartbeatId);
              }
              heartbeatId = setInterval("heartbeat()", timeoutSec * 1000);
              method = "getDefinedRoleRights";//获取座席权限
              send();

              info("签入成功");
              method = "getAccessnumOfAgent";//获取座席接入号
              send();
            } else if (retCode == '-53') {
              alert("用户名或密码错误，签入失败");
            } else {
              alert("签入失败[ErrorCode:" + retCode + "]");
            }
          } else if (methodName === 'agent_status_change') {
            if(jsonStr['agentno'] === this.agentno) {
              // 坐席状态改变
              this.agentStatus = parseInt(status);
            }
            if(this.showMonitor) {
              for (let i = 0; i < this.monitor.currentQueueAgents.length; i++) {
                let currentQueueAgent = this.monitor.currentQueueAgents[i];
                if(currentQueueAgent.agentNum == jsonStr['agentno']) {
                  currentQueueAgent.status = parseInt(status);
                  return;
                }
              }
              for (let i = 0; i < this.monitor.currentGroupAgents.length; i++) {
                let currentGroupAgent = this.monitor.currentGroupAgents[i];
                if(currentGroupAgent.agentNum == jsonStr['agentno']) {
                  currentGroupAgent.status = parseInt(status);
                  return;
                }
              }
            }
          } else if (methodName === 'disconnect') {
            hasResponse = true;
            hideLoadingMessage();
            signin = false;
            this.agentStatus = -1;
            if (heartbeatId >= 0) {
              clearInterval(heartbeatId);
            }
            if (changeStatusId >= 0) {
              clearInterval(changeStatusId);
            }
            setToolbarEnabled(false, false, false, false, false, false, false, false, false, false);
          } else if (methodName === 'common_callin_bridge_ring') {
            this.toSipAnswer(jsonStr);
          } else if (methodName === 'manual_callout_agent_ring') {
            this.toSipAnswer(jsonStr);
          } else if(methodName === 'get_queue_list') {
            this.monitor.roleQueueNum = jsonStr.queuenum.split(',');
            this.monitor.roleQueueName = jsonStr.queuename.split(',');
          } else if(methodName === 'get_agentgroup_list') {
            this.monitor.roleAgentGroupName = jsonStr.agentgroupname.split(',');
            this.monitor.roleAgentGroupNum = jsonStr.agentgroupnum.split(',');
          } else if(methodName === 'get_agents_of_queue') {
            let split = jsonStr.agentnum.split(",");
            this.monitor.currentQueueAgents = [];
            for (let i = 0; i < split.length; i++) {
              this.monitor.currentQueueAgents.push({
                agentNum: split[i],
                status: -1
              })
            }
          } else if(methodName === 'get_agents_of_agentgroup') {
            let split = jsonStr.agentnum.split(",");
            this.monitor.currentGroupAgents =[];
            for (let i = 0; i < split.length; i++) {
              this.monitor.currentGroupAgents.push({
                agentNum: split[i],
                status: -1
              })
            }
          }
          window.loading.close();
        }
      }
    }
  };
</script>
